<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CartItem extends Model
{
    use HasFactory;

    /**
     * 可批量赋值的属性
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'product_id',
        'quantity',
        'selected'
    ];

    /**
     * 获取关联的用户
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 获取关联的商品
     */
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * 获取总价
     */
    public function getTotalPriceAttribute()
    {
        return $this->product->price * $this->quantity;
    }

    /**
     * 验证规则
     */
    public static function rules()
    {
        return [
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1|max:99',
            'selected' => 'boolean'
        ];
    }

    /**
     * 错误消息
     */
    public static function messages()
    {
        return [
            'product_id.required' => '请选择商品',
            'product_id.exists' => '商品不存在',
            'quantity.required' => '请填写数量',
            'quantity.integer' => '数量必须为整数',
            'quantity.min' => '数量不能小于1',
            'quantity.max' => '数量不能超过99',
            'selected.boolean' => '选择状态不正确'
        ];
    }
}